package com.minisoft.ydac;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.nio.file.Paths;
import java.util.List;

public class BannerDownloader {

    private static final String CITY_LIST_URL = "https://zyt.cnhuafas.com/huafa/weixin/zyt/xcx/yq/public-api/api/salesCenter/getAll";
    private static final String BANNER_INFO_URL_TEMPLATE = "https://zyt.cnhuafas.com/huafa/weixin/zyt/xcx/yq/public-api/api/salesCenter/bannerInfo/%s/%s";
    private static final String SAVE_DIR = "d:/zyt-banner/";
    private static final String URL_FILE_PATH = "d:/zyt-banner/bannerUrl.txt";

    public static void main(String[] args) {
        // 获取城市列表
        JSONObject cityListJson = JSONUtil.parseObj(HttpRequest.get(CITY_LIST_URL).execute().body());
        JSONArray areas = cityListJson.getJSONObject("data").getJSONArray("areas");

        // 准备保存URL的文件
        FileUtil.touch(URL_FILE_PATH);

        // 遍历每个区域中的城市
        for (Object areaObj : areas) {
            JSONObject area = (JSONObject) areaObj;
            List<JSONObject> cityList = area.getJSONArray("list").toList(JSONObject.class);
            for (JSONObject city : cityList) {
                downloadCityBanners(city.getLong("pageId"), city.getStr("psn"));
            }
        }
    }

    private static void downloadCityBanners(Long pageId, String psn) {
        String bannerInfoUrl = String.format(BANNER_INFO_URL_TEMPLATE, pageId, psn);
        HttpResponse response = HttpRequest.get(bannerInfoUrl).execute();
        if (response.isOk()) {
            JSONObject bannerInfoJson = JSONUtil.parseObj(response.body());
            JSONArray banners = bannerInfoJson.getJSONArray("data");
            if (banners == null || banners.isEmpty()) {
                return;
            }
            for (Object bannerObj : banners) {
                JSONObject banner = (JSONObject) bannerObj;
                String bannerImgUrl = banner.getStr("bannerImgUrl");
                if (bannerImgUrl != null && !bannerImgUrl.isEmpty()) {
                    // 下载图片并保存路径
                    saveImageAndUrl(bannerImgUrl);
                }
            }
        }
    }

    private static void saveImageAndUrl(String imageUrl) {
        // 创建文件名（从url中提取）
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        String filePath = SAVE_DIR + fileName;
        //如果已存在，则不下载
        if (FileUtil.exist(filePath)) {
            return;
        }
        Console.log("下载图片：" + imageUrl);

        // 下载图片
        HttpRequest.get(imageUrl)
                .timeout(20000)
                .execute()
                .writeBody(filePath);

        // 保存URL到文本文件
        FileUtil.appendUtf8String(imageUrl + "\n", URL_FILE_PATH);
    }
}